package org.example.rabbitmq.server.route;

import org.example.rabbitmq.config.MultiQueueProperties;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.SmartLifecycle;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ProviderAutoConfig implements SmartLifecycle {
    boolean isRunning = false;
    @Autowired
    RabbitAdmin rabbitAdmin;
    @Autowired
    MultiQueueProperties multiQueueProperties;

    private void initQueues(int queueCount) {
        for (int i = 1; i <= queueCount; i++) {
            String queueName = multiQueueProperties.getQueueNameWithIndex(i);
            String routingKey = multiQueueProperties.getRoutingKeyWithIndex(i);
            rabbitAdmin.declareQueue(new Queue(queueName, true));
            rabbitAdmin.declareBinding(new Binding(queueName, Binding.DestinationType.QUEUE, multiQueueProperties.getExchangeName(), routingKey, null));
        }
    }


    @Override
    public void start() {
        isRunning = true;
        initQueues(multiQueueProperties.getQueueSize());
    }

    @Override
    public void stop() {
        isRunning = false;
    }

    @Override
    public boolean isRunning() {
        return isRunning;
    }
}